package org.kfive.nova.algorithm.binarytree;

/**
 * Your Trie object will be instantiated and called as such:
 * Trie trie = new Trie();
 * trie.insert("lintcode");
 * trie.search("lint"); will return false
 * trie.startsWith("lint"); will return true
 */
class TrieNode {
    // Initialize your data structure here.
    public TrieNode() {

    }

    char content;
    TrieNode[] childs = new TrieNode[26];
    int count;
    boolean isEnd;

}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        if(search(word))
            return;
        if(root!=null){
            TrieNode current = root;
            for(char c : word.toCharArray()){
                if(current.childs[(int)c-'a']!=null){
                    current = current.childs[(int)c-'a'];
                }else{
                    TrieNode node = new TrieNode();
                    node.content = c;
                    node.count = 1;
                    node.isEnd = false;
                    current.childs[(int)c-'a'] = node;
                    current = node;
                }
                current.count++;

            }
            current.isEnd = true;
        }
    }

    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode current = root;
        for(char c : word.toCharArray()){
            if(current.childs[(int)c-'a']==null){
                return false;
            }else{
                current = current.childs[(int)c-'a'];
            }
        }
        if(current.isEnd==true){
            return true;
        }else{
            return false;
        }
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        TrieNode current = root;
        for(char c : prefix.toCharArray()){
            if(current.childs[(int)c-'a']==null){
                return false;
            }else{
                current = current.childs[(int)c-'a'];
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("lintcode");
        System.out.println(trie.search("lint"));
        System.out.println(trie.startsWith("lint"));
    }
}